package cn.tedu.mall.seckill.interceptor;

import cn.tedu.mall.common.exception.CoolSharkServiceException;
import cn.tedu.mall.common.restful.ResponseCode;
import cn.tedu.mall.pojo.seckill.dto.SeckillOrderAddDTO;
import cn.tedu.mall.pojo.seckill.vo.SeckillSpuVO;
import cn.tedu.mall.seckill.service.impl.SeckillSpuServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * 验证提交的randCode 和下单商品所属spu是否是匹配的
 */
@Component
@Order(0)
public class RandCodeInterceptor implements SeckillInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void seckillCommitCheck(SeckillOrderAddDTO seckillOrderAddDTO) {
        //提交的参数randCode和redis保存spuVO的randCode对比
        //利用提交的参数spuId读取缓存数据 seckill:spu:2
        String spuVOKey =
                SeckillSpuServiceImpl.SECKILL_SPU_PREFIX + seckillOrderAddDTO.getSpuId();
        Object object = redisTemplate.opsForValue().get(spuVOKey);
        if (object == null) {
            throw new CoolSharkServiceException(
                    ResponseCode.NOT_FOUND, "无法找到对比验证randCode的对象");
        }
        SeckillSpuVO seckillSpuVO = (SeckillSpuVO) object;
        //先拿到预热生成的url地址
        String haveUrl = seckillSpuVO.getUrl();
        String commitUrl = "/seckill/" + seckillOrderAddDTO.getRandCode();
        if (!(haveUrl != null && haveUrl.equals(commitUrl))) {
            //说明randCode不符合要求,不是正确的randCode
            throw new CoolSharkServiceException(
                    ResponseCode.CONFLICT, "秒杀路径不正确");
        }
    }
}
